package com.ysd.lis.service.eq.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.BaseEntity;
import com.ysd.lis.entity.PubTaskPage;
import com.ysd.lis.entity.bac.BacCultrueInfo;
import com.ysd.lis.entity.eq.*;
import com.ysd.lis.mapper.eq.*;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.request.eq.EqPatrolPlanDto;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.eq.EqPatrolPlanEqStItService;
import com.ysd.lis.service.eq.EqPatrolPlanEqStService;
import com.ysd.lis.service.eq.EqPatrolPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备巡检计划 服务实现类
 * </p>
 *
 * @author WH
 * @since 2024-08-23
 */
@Service
public class EqPatrolPlanServiceImpl extends ServiceImpl<EqPatrolPlanMapper, EqPatrolPlan> implements EqPatrolPlanService {

    @Autowired
    private EqPatrolPlanMapper eqPatrolPlanMapper;
    @Autowired
    private EqPatrolTaskMapper eqPatrolTaskMapper;
    @Autowired
    public SysRuleSetService sysRuleSetService;
    @Autowired
    private EqPatrolPlanEqMapper eqPatrolPlanEqMapper;
    @Autowired
    private EqPatrolTaskEqMapper eqPatrolTaskEqMapper;
    @Autowired
    private EqPatrolTaskEqStMapper eqPatrolTaskEqStMapper;
    @Autowired
    private EqPatrolTaskEqStItMapper eqPatrolTaskEqStItMapper;
    @Autowired
    private EqPatrolPlanEqStMapper eqPatrolPlanEqStMapper;
    @Autowired
    private EqPatrolPlanEqStService eqPatrolPlanEqStService;
    @Autowired
    private EqPatrolPlanEqStItService eqPatrolPlanEqStItService;

    @Override
    public Result findPatrolPlanPageList(CommonPageDto pageParam) {
        Page<EqPatrolPlan> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<EqPatrolPlan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EqPatrolPlan::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(EqPatrolPlan::getCode, pageParam.getSeachValue()).or().like(EqPatrolPlan::getName, pageParam.getSeachValue()));
        }
        lambdaQueryWrapper.orderByDesc(EqPatrolPlan::getCreateTime);
        Page<EqPatrolPlan> orderPage = eqPatrolPlanMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", orderPage);
    }

    @Override
    public Result findPatrolList(EqPatrolPlanDto eqPatrolPlanDto) {

        LambdaQueryWrapper<EqPatrolPlan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(eqPatrolPlanDto.getBeginTime()) && StringUtils.isNotBlank(eqPatrolPlanDto.getEndTime())) {
            Timestamp startTime = Timestamp.valueOf(eqPatrolPlanDto.getBeginTime() + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(eqPatrolPlanDto.getEndTime() + " 23:59:59");
            lambdaQueryWrapper.ge(EqPatrolPlan::getEndTime, startTime);
            lambdaQueryWrapper.le(EqPatrolPlan::getEndTime, endTime);
        }

        lambdaQueryWrapper.eq(StringUtils.isNotBlank(eqPatrolPlanDto.getHandler()), EqPatrolPlan::getHandler, eqPatrolPlanDto.getHandler());
        lambdaQueryWrapper.eq(EqPatrolPlan::getDelFlag, 0);
        if (StringUtils.isNotBlank(eqPatrolPlanDto.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(EqPatrolPlan::getCode, eqPatrolPlanDto.getSeachValue()).or().like(EqPatrolPlan::getName, eqPatrolPlanDto.getSeachValue()));
        }
        lambdaQueryWrapper.orderByAsc(EqPatrolPlan::getEndTime);
        List<EqPatrolPlan> eqPatrolPlanList = eqPatrolPlanMapper.selectList(lambdaQueryWrapper);
        for (EqPatrolPlan patrolPlan : eqPatrolPlanList) {
            MPJLambdaWrapper<EqPatrolTask> patrolTaskWrapper = new MPJLambdaWrapper<>();
            patrolTaskWrapper.selectCount(EqPatrolTask::getStatus, EqRepairOrder::getRepairStatusCnt)
                    .selectAs(EqPatrolTask::getStatus, EqPatrolTask::getStatus)
                    .eq(EqPatrolTask::getDelFlag,0)
                    .eq(EqPatrolTask::getPlanId, patrolPlan.getId())
                    .groupBy(EqPatrolTask::getStatus);
            List<EqPatrolTask> patrolTaskList = eqPatrolTaskMapper.selectList(patrolTaskWrapper);
            Map<String, Optional<EqPatrolTask>> taskMap = patrolTaskList.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.groupingBy(EqPatrolTask::getStatus,
                            Collectors.reducing((a, b) -> a)));
            //待检
            Optional<EqPatrolTask> eqPatrolTask0 = taskMap.get("0");
            Integer shouldCnt =Objects.nonNull(eqPatrolTask0)? eqPatrolTask0.get().getRepairStatusCnt() :0;
            //在检
            Optional<EqPatrolTask> eqPatrolTask5 = taskMap.get("5");
            Integer rightCnt =Objects.nonNull(eqPatrolTask5)? eqPatrolTask5.get().getRepairStatusCnt() :0;
            //已检
            Optional<EqPatrolTask> eqPatrolTask10 = taskMap.get("10");
            Integer noCnt = Objects.nonNull(eqPatrolTask10)? eqPatrolTask10.get().getRepairStatusCnt() :0;

            patrolPlan.setShouldPatrol(shouldCnt+rightCnt+noCnt);
            patrolPlan.setRightPatrol(rightCnt+noCnt);
            patrolPlan.setNoPatrol(shouldCnt);

            //巡检设备概况
            MPJLambdaWrapper<EqPatrolTaskEq> patrolTaskEqWrapper = new MPJLambdaWrapper<>();
            patrolTaskEqWrapper.selectAll(EqPatrolTaskEq.class)
                    .eq(EqPatrolTaskEq::getDelFlag,0)
                    .eq(EqPatrolTaskEq::getPlanId,patrolPlan.getId()) ;
            List<EqPatrolTaskEq> patrolTaskEqList = eqPatrolTaskEqMapper.selectList(patrolTaskEqWrapper);
            long noDetectionCount = patrolTaskEqList.stream().filter(item -> StringUtils.isNotBlank(item.getNoCheck())).map(BaseEntity::getId).count();
            long rigntCount = patrolTaskEqList.stream().filter(item -> StringUtils.isBlank(item.getNoPass())).filter(item -> StringUtils.isBlank(item.getNoCheck())).map(BaseEntity::getId).count();
            long shouldInspected =patrolTaskEqList.size();
            long realityInspected =noDetectionCount+rigntCount;
            long noPassCount = patrolTaskEqList.stream().filter(item -> StringUtils.isNotBlank(item.getNoPass())).filter(item -> StringUtils.isBlank(item.getNoCheck())).map(BaseEntity::getId).count();
            patrolPlan.setShouldInspected((int) shouldInspected);
            patrolPlan.setRealityInspected((int) realityInspected);
            patrolPlan.setNoPassCount((int) noPassCount);
        }
        return Result.succ(1, "查询成功", eqPatrolPlanList);
    }

    @Override
    public Result addPatrolPlan(EqPatrolPlan eqPatrolPlan) {
        //添加设备巡检任务
        String a = sysRuleSetService.createRuleCodeList("EqPatrolPlanCode", 1).get(0);
        eqPatrolPlan.setCode(a);
        eqPatrolPlanMapper.insert(eqPatrolPlan);
        List<EqPatrolPlanEq> patrolPlanEqList = eqPatrolPlan.getPatrolPlanEqList();
        if (CollectionUtils.isNotEmpty(patrolPlanEqList)) {
            for (EqPatrolPlanEq eqPatrolPlanEq : patrolPlanEqList) {
                eqPatrolPlanEq.setPlanId(eqPatrolPlan.getId());
                //添加设备巡检任务设备
                eqPatrolPlanEqMapper.insert(eqPatrolPlanEq);
                List<EqPatrolPlanEqSt> patrolPlanEqStList = eqPatrolPlanEq.getPatrolPlanEqStList();
                List<EqPatrolPlanEqStIt> patrolPlanEqStItList = eqPatrolPlanEq.getPatrolPlanEqStItList();


                //添加巡检任务设备的巡检标准
                for (EqPatrolPlanEqSt eqPatrolPlanEqSt : patrolPlanEqStList) {
                    eqPatrolPlanEqSt.setPlanId(eqPatrolPlan.getId());
                    eqPatrolPlanEqSt.setPlanEqId(eqPatrolPlanEq.getId());
                    eqPatrolPlanEqStMapper.insert(eqPatrolPlanEqSt);
                    List<EqPatrolPlanEqStIt> eqPatrolPlanEqStIts = patrolPlanEqStItList.stream().filter(item -> item.getStandardId().equals(eqPatrolPlanEqSt.getStandardId())).collect(Collectors.toList());
                    //添加巡检任务设备的巡检标准项
                    if (CollectionUtils.isNotEmpty(eqPatrolPlanEqStIts)) {
                        for (EqPatrolPlanEqStIt eqPatrolPlanEqStIt : eqPatrolPlanEqStIts) {
                            eqPatrolPlanEqStIt.setPlanId(eqPatrolPlan.getId());
                            eqPatrolPlanEqStIt.setPlanEqId(eqPatrolPlanEq.getId());
                            eqPatrolPlanEqStIt.setPlanEqStId(eqPatrolPlanEqSt.getId());
                        }
                        eqPatrolPlanEqStItService.saveBatch(eqPatrolPlanEqStIts);
                    }
                }
            }
        }
        return Result.succ(1, "添加成功", eqPatrolPlan);
    }

    @Override
    public Result findPatrolPlanById(EqPatrolPlan eqPatrolPlan) {
        EqPatrolPlan eqPatrolPlan1 = eqPatrolPlanMapper.selectById(eqPatrolPlan.getId());
        List<EqPatrolPlanEq> eqPatrolPlanEqs = eqPatrolPlanEqMapper.selectList(new LambdaQueryWrapper<EqPatrolPlanEq>().eq(EqPatrolPlanEq::getPlanId, eqPatrolPlan1.getId()).eq(EqPatrolPlanEq::getDelFlag, 0));
        for (EqPatrolPlanEq eqPatrolPlanEq : eqPatrolPlanEqs) {
            List<EqPatrolPlanEqSt> eqPatrolPlanEqSts = eqPatrolPlanEqStMapper.selectList(new LambdaQueryWrapper<EqPatrolPlanEqSt>().eq(EqPatrolPlanEqSt::getPlanEqId, eqPatrolPlanEq.getId()).eq(EqPatrolPlanEqSt::getDelFlag, 0));
            List<EqPatrolPlanEqStIt> eqPatrolPlanEqStIts = eqPatrolPlanEqStItService.list(new LambdaQueryWrapper<EqPatrolPlanEqStIt>().eq(EqPatrolPlanEqStIt::getPlanEqId, eqPatrolPlanEq.getId()).eq(EqPatrolPlanEqStIt::getDelFlag, 0));
            eqPatrolPlanEq.setPatrolPlanEqStList(eqPatrolPlanEqSts);
            eqPatrolPlanEq.setPatrolPlanEqStItList(eqPatrolPlanEqStIts);
        }
        eqPatrolPlan1.setPatrolPlanEqList(eqPatrolPlanEqs);
        return Result.succ(1, "查询成功", eqPatrolPlan1);
    }

    @Override
    public Result deletePatrolPlan(List<EqPatrolPlan> eqPatrolPlan) {
        List<String> ids = eqPatrolPlan.stream().map(EqPatrolPlan::getId).collect(Collectors.toList());
        eqPatrolPlanMapper.deleteBatchIds(ids);
        eqPatrolPlanEqMapper.delete(new LambdaQueryWrapper<EqPatrolPlanEq>().in(EqPatrolPlanEq::getPlanId, ids).eq(EqPatrolPlanEq::getDelFlag, 0));
        eqPatrolPlanEqStMapper.delete(new LambdaQueryWrapper<EqPatrolPlanEqSt>().in(EqPatrolPlanEqSt::getPlanId, ids).eq(EqPatrolPlanEqSt::getDelFlag, 0));
        eqPatrolPlanEqStItService.remove(new LambdaQueryWrapper<EqPatrolPlanEqStIt>().in(EqPatrolPlanEqStIt::getPlanId, ids).eq(EqPatrolPlanEqStIt::getDelFlag, 0));
        return Result.succ(1, "删除巡检任务成功", "");
    }

    @Override
    public Result editPatrolPlan(EqPatrolPlan eqPatrolPlan) {
        eqPatrolPlanMapper.updateById(eqPatrolPlan);
        List<EqPatrolPlanEq> patrolPlanEqList = eqPatrolPlan.getPatrolPlanEqList();
        if (CollectionUtils.isNotEmpty(patrolPlanEqList)) {
            for (EqPatrolPlanEq eqPatrolPlanEq : patrolPlanEqList) {
                eqPatrolPlanEqMapper.updateById(eqPatrolPlanEq);
                List<EqPatrolPlanEqSt> patrolPlanEqStList = eqPatrolPlanEq.getPatrolPlanEqStList();
                List<EqPatrolPlanEqStIt> patrolPlanEqStItList = eqPatrolPlanEq.getPatrolPlanEqStItList();
                if (CollectionUtils.isNotEmpty(patrolPlanEqStList)) {
                    eqPatrolPlanEqStService.saveOrUpdateBatch(patrolPlanEqStList);
                }
                if (CollectionUtils.isNotEmpty(patrolPlanEqStItList)) {
                    eqPatrolPlanEqStItService.saveOrUpdateBatch(patrolPlanEqStItList);
                }
            }
        }
        return Result.succ(1, "编辑成功", eqPatrolPlan);
    }

    @Override
    public Result patrolPlanStopStart(EqPatrolPlan eqPatrolPlan) {
        eqPatrolPlanMapper.updateById(eqPatrolPlan);
        return Result.succ(1, "操作成功", null);
    }

    @Override
    public Result handleExecutePlan(EqPatrolPlan eqPatrolPlan) {
        String a = sysRuleSetService.createRuleCodeList("EqPatrolTaskCode", 1).get(0);
        //新增任务
        EqPatrolPlan patrolPlan = eqPatrolPlanMapper.selectById(eqPatrolPlan.getId());
        EqPatrolTask eqPatrolTask = new EqPatrolTask();
        BeanUtil.copyProperties(patrolPlan, eqPatrolTask);
        eqPatrolTask.setId(null);
        eqPatrolTask.setPlanId(patrolPlan.getId());
        eqPatrolTask.setCode(a);
        eqPatrolTask.setStatus("0");
        eqPatrolTaskMapper.insert(eqPatrolTask);
        List<EqPatrolPlanEq> eqPatrolPlanEqs = eqPatrolPlanEqMapper.selectList(new LambdaQueryWrapper<EqPatrolPlanEq>().eq(EqPatrolPlanEq::getPlanId, eqPatrolPlan.getId()).eq(EqPatrolPlanEq::getDelFlag, 0));
        for (EqPatrolPlanEq eqPatrolPlanEq : eqPatrolPlanEqs) {
            EqPatrolTaskEq eqPatrolTaskEq = new EqPatrolTaskEq();
            BeanUtil.copyProperties(eqPatrolPlanEq, eqPatrolTaskEq);
            eqPatrolTaskEq.setId(null);
            eqPatrolTaskEq.setTaskId(eqPatrolTask.getId());
            eqPatrolTaskEq.setPlanId(eqPatrolPlan.getId());
            eqPatrolTaskEq.setPlanEqId(eqPatrolPlanEq.getId());
            eqPatrolTaskEqMapper.insert(eqPatrolTaskEq);
            List<EqPatrolPlanEqSt> eqPatrolPlanEqSts = eqPatrolPlanEqStMapper.selectList(new LambdaQueryWrapper<EqPatrolPlanEqSt>().eq(EqPatrolPlanEqSt::getPlanId, eqPatrolPlan.getId()).eq(EqPatrolPlanEqSt::getDelFlag, 0));
            List<EqPatrolPlanEqStIt> eqPatrolPlanEqStIts = eqPatrolPlanEqStItService.list(new LambdaQueryWrapper<EqPatrolPlanEqStIt>().in(EqPatrolPlanEqStIt::getPlanId, eqPatrolPlan.getId()).eq(EqPatrolPlanEqStIt::getDelFlag, 0));

            for (EqPatrolPlanEqSt eqPatrolPlanEqSt : eqPatrolPlanEqSts) {
                EqPatrolTaskEqSt eqPatrolTaskEqSt = new EqPatrolTaskEqSt();
                BeanUtil.copyProperties(eqPatrolPlanEqSt, eqPatrolTaskEqSt);
                eqPatrolTaskEqSt.setId(null);
                eqPatrolTaskEqSt.setTaskId(eqPatrolTask.getId());
                eqPatrolTaskEqSt.setTaskEqId(eqPatrolTaskEq.getId());
                eqPatrolTaskEqSt.setPlanId(eqPatrolPlan.getId());
                eqPatrolTaskEqSt.setPlanEqId(eqPatrolPlanEq.getId());
                eqPatrolTaskEqSt.setPlanEqStId(eqPatrolPlanEqSt.getId());
                eqPatrolTaskEqStMapper.insert(eqPatrolTaskEqSt);
                List<EqPatrolPlanEqStIt> eqPatrolPlanEqStItList = eqPatrolPlanEqStIts.stream().filter(item -> item.getPlanEqStId().equals(eqPatrolPlanEqSt.getId())).collect(Collectors.toList());
                for (EqPatrolPlanEqStIt eqPatrolPlanEqStIt : eqPatrolPlanEqStItList) {
                    EqPatrolTaskEqStIt eqPatrolTaskEqStIt = new EqPatrolTaskEqStIt();
                    BeanUtil.copyProperties(eqPatrolPlanEqStIt, eqPatrolTaskEqStIt);
                    eqPatrolTaskEqStIt.setId(null);
                    eqPatrolTaskEqStIt.setTaskId(eqPatrolTask.getId());
                    eqPatrolTaskEqStIt.setTaskEqId(eqPatrolTaskEq.getId());
                    eqPatrolTaskEqStIt.setTaskEqStId(eqPatrolTaskEqSt.getId());
                    eqPatrolTaskEqStIt.setPlanId(eqPatrolPlan.getId());
                    eqPatrolTaskEqStIt.setPlanEqId(eqPatrolPlanEq.getId());
                    eqPatrolTaskEqStIt.setPlanEqStId(eqPatrolPlanEqSt.getId());
                    eqPatrolTaskEqStIt.setPlanEqStItId(eqPatrolPlanEqStIt.getId());
                    eqPatrolTaskEqStItMapper.insert(eqPatrolTaskEqStIt);
                }
            }
        }
        return Result.succ(1, "执行成功", null);
    }
}
